#!/bin/sh
#
# 简单写一下脚本的功能。
#
#
#

workdir=~/workshop/gitee/3place/

if [ $# -ne 0 ]; then
	echo "Usage: this is a empty shell."
	exit
fi

cd $workdir

if find . -mnewer index_booklist.md|grep -q -w BOOKLIST.md ; then
	echo "some list change"
else
	exit 0
fi

cat `find .|grep -w BOOKLIST.md` |sort |uniq >tmp.booklist.md

echo  "% 书单@第三同读" > index_booklist.md

echo  "" >> index_booklist.md

booksinlist=`find .|grep -w BOOKLIST.md |xargs file|sed -e "/empty/d"|awk -F: '{print $1}'|sort -g `

#echo $booksinlist

#exit

commcode header >> index_booklist.md

for files in `cat tmp.booklist.md`
do
	echo "% $files " >$files.md
	echo "[$files](/booklist/$files.html) " >>index_booklist.md

	echo "" >> $files.md

	commcode header >> $files.md

	echo "" >>index_booklist.md

	for dirs in $booksinlist
	do
		grep $files $dirs >/dev/null
		if [ $? -eq 0 ]; then
			localdir=`echo $dirs |awk -F "BOOKLIST.md" '{print $1}'`
			if [ -e $localdir/config ]; then  # 避免有BOOKLIST，却没有config的情况。
				source $localdir/config
				echo "[$bookname]($url)" >>$files.md
				echo "" >> $files.md
			fi

		fi
	done

	pandoc -s $files.md -o ~/workshop/hbaolong.github.io/booklist/$files.html

	rm -f $files.md

done

pandoc -s index_booklist.md -o ~/workshop/hbaolong.github.io/booklist/index.html

#rm -f index_booklist.md

rm -f tmp.booklist.md
